package com.guoguo.leetcode.character;

/**
 * @Author guoguo
 * @desc 反转字符串
 * leetcode地址:
 * <url>https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnhbqj/</url>
 */
public class Reverse {

    public static void main(String[] args) {
        reverse("abcde");
    }

    /**
     * 反转字符串
     */
    private static void reverse(String s){
        char[] charArray = s.toCharArray();
        for(int left=0,right=s.length()-1; left<right; left++,right--){
            char temp = charArray[left];
            charArray[left] = charArray[right];
            charArray[right] = temp;
        }
        System.out.println(String.valueOf(charArray));
    }

    /**
     * 递归的方式处理
     * @param s
     */
    public void reverseString(char[] s) {
        if (s == null || s.length == 0)
            return;
        reverseStringHelper(s, 0, s.length - 1);
    }

    public void reverseStringHelper(char[] s, int left, int right) {
        if (left >= right)
            return;
        swap(s, left, right);
        reverseStringHelper(s, ++left, --right);
    }

    private void swap(char[] array, int i, int j) {
        char temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

}
